<template>
  <div class="request-party-service-manage">
    <div class="app-container">
      <div class="mainbox">
        <Header :header-name="$route.meta.title" />
        <div class="request-party-service-manage-body">
          <!-- 搜索板块 -->
          <el-form ref="form" :model="form" inline label-width="80px" class="search-form">
            <el-form-item prop="monitorName">
              <el-input v-model="form.monitorName" clearable placeholder="设备名称" />
            </el-form-item>
            <el-form-item prop="monitorIp">
              <el-input v-model="form.monitorIp" clearable placeholder="设备IP" />
            </el-form-item>
            <el-form-item prop="systemId">
              <el-select v-model="form.systemId" clearable placeholder="请选择系统名称">
                <el-option
                  v-for="(item, index) in systemIdList"
                  :key="index"
                  :label="item.systemCode + ' / ' + item.systemName"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
            <el-form-item class="query-action">
              <el-button :loading="loading" @click="resetBtn"> 重置</el-button>
              <el-button type="primary" @click="getTableData"> 查询</el-button>
              <el-button v-permission="['CAMERASTATEWATCH_ADD_BUTTON']" type="primary" @click="addBtn"> 新增</el-button>
              <!--              <el-button v-permission="['CAMERASTATEWATCH_DEL_BUTTON']" :disabled="ids.length === 0" type="danger" @click="delBtn"> 删除 </el-button>-->
            </el-form-item>
          </el-form>

          <!-- 表格数据视图 -->
          <div>
            <FlexTable
              v-loading="loading"
              border
              :data="tableData"
              :columns="columnsOptions"
              @selection-change="handleSelectionChange"
            />
            <el-pagination
              :page-size="pagination.pageSize"
              :current-page.sync="pagination.pageNo"
              layout="prev, pager, next, jumper"
              :total="pagination.totalPage"
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
            />
          </div>
        </div>
        <create-service ref="createService" :manage-type="2" @interfaceServiceRefresh="getTableData" />
        <monitor-log ref="monitorLog" />
      </div>
    </div>
  </div>
</template>

<script>
import MonitorLog from '@/views/serviceMonitor/monitorLog.vue'
import CreateService from './components/addEditDataWatch'
import { getSystemListApi } from '@/api/serviceManage/requestPartyServiceManage'
import { deleteApi, pageApi, detailApi } from '@/api/cameraMonitor/cameraMonitor'
import dictMixin from '@/utils/mixins/dict'
import { changeTaskStatus } from '@/api/serviceWatch'
import { editRes } from '@/utils/editAlarmUser'

export default {
  name: 'CameraStateWatch',
  components: {
    CreateService,
    MonitorLog
  },
  mixins: [
    dictMixin(['monitorFactory@Local'])
  ],
  data() {
    return {
      ids: [],
      dataList: null,
      dialogVisible: false,
      form: {
        monitorName: '',
        monitorIp: '',
        systemId: ''
      },
      systemIdList: [],
      loading: false,
      tableData: [],
      columnsOptions: [
        { type: 'selection' },
        { label: '设备名称', prop: 'monitorName' },
        {
          label: '设备厂商', prop: 'monitorFactory',
          customRender: scope => {
            return this.getDictText('monitorFactory', scope.row.monitorFactory)
          }
        },
        { label: '设备IP', prop: 'monitorIp' },
        { label: '系统名称', prop: 'systemName' },
        { label: '创建时间', prop: 'createTime' },
        { label: '创建人', prop: 'createUserName' },
        { label: '备注', prop: 'remarks' },
        {
          label: '操作', width: 200,
          customRender: (scope) => {
            return [
              <el-button vPermission={['CAMERASTATEWATCH_STARTSTOP_BUTTON']} type='text' onClick={() => this.changeType(scope.row)}> {scope.row.taskStatus === '1' ? '停止' : '启用'} </el-button>,
              <el-button vPermission={['CAMERASTATEWATCH_SHOW_BUTTON']} type='text' onClick={() => this.show(scope.row)}> 连接详情 </el-button>,
              <el-button vPermission={['CAMERASTATEWATCH_UPDATE_BUTTON']} type='text' onClick={() => this.edit(scope.row)}> 修改 </el-button>,
              <el-button vPermission={['CAMERASTATEWATCH_DEL_BUTTON']} type='text' class='text-del-btn' onClick={() => this.delBtn(scope.row)}> 删除 </el-button>
            ]
          }
        }
      ],
      pagination: {
        pageNo: 1,
        pageSize: 10,
        totalPage: 1
      }
    }
  },
  created() {
    // 获取系统
    getSystemListApi()
      .then(({ code, data }) => {
        if (code === '00000') {
          this.systemIdList = data
        }
      })
    this.getTableData()
  },
  methods: {
    handleSelectionChange(val) {
      this.ids = []
      this.ids = val.map(item => {
        return item.id
      })
    },
    show(row) {
      this.$refs.monitorLog.init(row.id, 2, row.monitorName, row.monitorIp)
    },
    changeType(val) {
      const data = {
        ids: [val.id],
        type: '2',
        taskStatus: val.taskStatus === '1' ? '2' : '1'
      }
      changeTaskStatus(data).then(res => {
        if (res.data === true) {
          this.$message.success(data.taskStatus === '1' ? '启用成功' : '停用成功')
          this.getTableData()
        } else {
          this.$message.success(data.taskStatus === '1' ? '启用失败' : '停用失败')
        }
      })
    },
    handleSizeChange(val) {
      this.pagination.pageSize = val
      this.getTableData()
    },
    handleCurrentChange(val) {
      this.pagination.pageNo = val
      this.getTableData()
    },
    getTableData() {
      this.setLoading(true)
      pageApi({
        pageNo: this.pagination.pageNo,
        pageSize: this.pagination.pageSize,
        monitorName: this.form.monitorName,
        monitorIp: this.form.monitorIp,
        systemId: this.form.systemId
      }).then(({ code, data }) => {
        if (code === '00000') {
          this.tableData = data.rows
          this.pagination.totalPage = data.totalRows
          this.pagination.pageNo = data.pageNo
          this.pagination.pageSize = data.pageSize
        }
      }).finally(() => {
        this.setLoading(false)
      })
    },
    getDictText(dictName, value) {
      const dict = this.dictOptions[dictName]
      if (dict) {
        // eslint-disable-next-line eqeqeq
        const target = dict.find(item => item.value == value)?.label
        return target ?? value
      }
      return value
    },
    resetBtn() {
      this.form = {
        monitorName: '',
        monitorIp: '',
        systemId: ''
      }
      Object.assign(this.pagination, {
        pageNo: 1,
        pageSize: 10,
        totalPage: 0
      })
      this.getTableData()
    },
    // 新增按钮
    addBtn() {
      this.$refs.createService.dialogVisible = true
      this.$refs.createService.disabled = true
      this.$refs.createService.form = { taskStatus: '1' }
      this.$refs.createService.getInitData()
    },
    edit(row) {
      this.$refs.createService.disabled = false
      detailApi({ id: row.id }).then(res => {
        const data = JSON.parse(JSON.stringify(res.data))
        data.alarmUsers = editRes(data.alarmUsers)
        this.$refs.createService.form = data
        this.$refs.createService.dialogVisible = true
        this.$refs.createService.getInitData(row)
      })
    },
    async delBtn(row) {
      this.$confirm('是否删除该条数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // const ids = row.id ? row.id : this.ids
        deleteApi({
          id: row.id
        })
          .then(({ code }) => {
            if (code === '00000') {
              this.showMessage('success', '删除成功')
              this.getTableData()
            }
          })
      })
    },
    setLoading(loading) {
      this.loading = loading
    },
    showMessage(type, message) {
      this.$message[type](message)
    }
  }
}
</script>

<style lang="scss" scoped>
.request-party-service-manage {
  background: #F2F2F2;

  &-body {
    background: #fff;
    margin-top: 10px;
    padding: 20px;
    height: calc(100vh - 254px);
    overflow-y: auto;
  }

  .el-pagination {
    text-align: right;
    margin-top: 20px;
  }

  .el-tree {
    ::v-deep .el-tree-node__expand-icon {
      font-size: 18px;
    }

    .custom-tree-node {
      width: calc(100% - 30px);
      display: flex;
      align-items: center;
      padding-right: 20px;

      > span:first-child {
        display: inline-block;
        width: calc(100% - 50px);
        overflow: hidden;
        white-space: nowrap;
        text-overflow: ellipsis;
        line-height: 40px;
      }

      .tree-btn {
        .el-switch {
          margin-top: -4px;
          margin-left: 10px;
        }
      }
    }
  }
}
</style>

